# This defines all our data types that are stored in Google's database
from astarclasses import *
from google.appengine.api import urlfetch
from appengine_utilities import sessions
from google.appengine.api import channel
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import images
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from datetime import datetime
from string import Template
import string
from string import *
import cgi
import os
import logging
import sys
import time # to sleep
from django.utils import simplejson as json


from astarutils import * # this defines helpful functions like friendly date delta format


class RateTopic(webapp.RequestHandler):
	def getRankings(self, talk):
		topics_query =  db.GqlQuery("SELECT * FROM Topic WHERE ANCESTOR IS :1 ORDER BY avg_ranking", talk)
		topics_list = []
		sort_index = 1
		for topic in topics_query:
			topics_list.append({'key':str(topic.key()), 
			'data_id':'topic-'+str(topic.key().id()), 
			'num_very_interested':topic.num_very_interested, 
			'avg_ranking':round(50*topic.avg_ranking + 50, 1),
			'sort_index':sort_index})
			sort_index += 1
		message = {'success':'ok', 'message':'rankings_changed', 'topics_list':topics_list}
		return(message)
		
	def get(self):
		talk_key = self.request.get("talk_key")
		talk = Talk.get(talk_key)
		if talk:
			message = json.dumps(self.getRankings(talk))
		else:
			message = json.dumps({'error':'No talk found with id:'+talk_short_title})
		self.response.out.write(message);
			
		
	def post(self):
		topic_key = self.request.get("topic_key")
		try:
			topic = Topic.get(topic_key)
		except:
			topic = None
		if topic:
			talk_key = topic.parent_key()
			talk = Talk.get(talk_key)
			self.sess = sessions.Session() # get the unique session id to identify this client
			star = None # begin by assuming that no user (star) has been created for this session
			if self.sess.has_key("star_key"): # try to find a star associated with this session
				star = Star.get(self.sess["star_key"])
			if star:
				rating_string = self.request.get("rate")
				try:
					rating_value = int(rating_string)
				except:
					rating_value = -1000
				if (rating_value > 0):
					rating_query = TopicRating.gql("WHERE topic =:1 AND star =:2", topic, star)
					rating = rating_query.get() # see if there is already a rating for this user for this topic
					if not rating: # if this user hasn't already rated this topic
						rating = TopicRating(parent=topic, topic=topic, star=star, value=rating_value)
						topic.avg_rating = ((topic.avg_rating * topic.num_ratings) + rating_value) / (topic.num_ratings + 1)
						topic.num_ratings += 1
					else: # this user is CHANGING their rating of this topic, so the math is slightly different
						old_rating = rating.value
						new_rating = rating_value
						rating.value = new_rating
						topic.avg_rating = ((topic.avg_rating * topic.num_ratings) - old_rating + new_rating) / topic.num_ratings
					rating.put()
					topic.put()
					# we used to send notification to all presenters here but now we have presenters pull 
					self.response.out.write(json.dumps({'success':'ok'}))
				else:
					self.response.out.write(json.dumps({'error':'Invalid rating ('+self.request.get('rating_value')+'). Valid choices are positive integers'}))
			else:
				self.response.out.write(json.dumps({'error':'Could not save rating because you have no current session. Try enabling cookies and refreshing the page.'}))
		else:
			self.response.out.write(json.dumps({'error':'Could not save rating due to invalid topic id %d' % topic_id}))	
		


			
	
application = webapp.WSGIApplication([('/ratetopic/rate', RateTopic),
									   ('/ratetopic/getratngs', RateTopic),
					  ],
				     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
